﻿#include <stddef.h>
#include "UniverTab.h"

UniverTabItem::~UniverTabItem()
{
}

UniverTab::UniverTab(size_t cubage)
{
    m_groupCubage = cubage;
    m_allocTotal = 0;
    m_itemTotal = 0;
}

UniverTab::~UniverTab()
{
    size_t i;
    if (m_groups.size())
    {
        for (i = 0; i < m_groups.size(); i++)
            delete[] (m_groups[i]);
        m_groups.clear();
    }
}

void UniverTab::increaseGroupAlloc()
{
    m_allocTotal += m_groupCubage;
    UniverTabItem* groupdata = allocGroupData(m_groupCubage);
    m_groups.push_back(groupdata);
}

size_t UniverTab::moveItemInto(UniverTabItem & item)
{
    return moveItemInto(&item);
}

size_t UniverTab::moveItemInto(UniverTabItem * pItem)
{
    size_t cur_pos;
    size_t cur_group;

    if (m_itemTotal >= m_allocTotal)
        increaseGroupAlloc();

    cur_group = m_itemTotal / m_groupCubage;
    cur_pos = m_itemTotal % m_groupCubage;

    UniverTabItem* groupdata = m_groups[cur_group];
    UniverTabItem* pSlot = groupdata->getOffsetItem(cur_pos);
    pSlot->moveFrom(pItem);

    m_itemTotal++;
    return (m_itemTotal - 1);
}

size_t UniverTab::copyItemInto(const UniverTabItem & item)
{
    return copyItemInto(&item);
}

size_t UniverTab::copyItemInto(const UniverTabItem * pItem)
{
    size_t cur_pos;
    size_t cur_group;

    if (m_itemTotal >= m_allocTotal)
        increaseGroupAlloc();

    cur_group = m_itemTotal / m_groupCubage;
    cur_pos = m_itemTotal % m_groupCubage;

    UniverTabItem* groupdata = m_groups[cur_group];
    UniverTabItem* pSlot = groupdata->getOffsetItem(cur_pos);
    pSlot->copyFrom(pItem);

    m_itemTotal++;
    return (m_itemTotal - 1);
}


UniverTabItem* UniverTab::getItem(size_t index)
{
    size_t group_idx, item_idx;
    UniverTabItem* groupdata;

    if (index >= m_itemTotal)
        return NULL;
    group_idx = index / m_groupCubage;
    item_idx = index % m_groupCubage;

    groupdata = m_groups[group_idx];

    return groupdata->getOffsetItem(item_idx);
}

size_t UniverTab::getTotalCount(void)
{
    return m_itemTotal;
}





